<template>
  <div class="flex-1 page_contain">
    <div class="app-container">
      <!-- 搜索框 -->
      <div class="search-container" :class="isContrast ? 'is-contrast' : ''">
        <el-form :model="searchParam" :inline="true" label-width="72px">
          <!-- <el-form-item label="工段">
            <el-select
              v-model="searchParam.workshopSectionId"
              placeholder="请选择工段"
              clearable
              filterable
              @change="changeWorkshopSection"
            >
              <el-option
                v-for="item in workshopSectionList"
                :key="item.id"
                :label="item.workshopSectionCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="工序">
            <el-select
              v-model="searchParam.processCode"
              placeholder="请选择工序"
              clearable
              filterable
              @change="processChange"
            >
              <el-option
                v-for="item in processCodeList"
                :key="item.processCode"
                :label="item.processName"
                :value="item.processCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="生产线">
            <el-select
              v-model="searchParam.processEquipId"
              placeholder="请选择生产线"
              clearable
              filterable
              @change="processEquipChange"
            >
              <el-option
                v-for="item in processEquipList"
                :key="item.id"
                :label="item.equipCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备">
            <el-select
              v-model="searchParam.deviceId"
              placeholder="请选择设备"
              clearable
              filterable
              @change="equipChange"
              class="select-device"
            >
              <el-option
                v-for="item in equipList"
                :key="item.equipId"
                :label="item.equipName"
                :value="item.equipId"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="型号描述">
            <el-select
              v-model="searchParam.productModel"
              placeholder="请选择型号描述"
              clearable
              filterable
              :filter-method="customFilter1"
              @change="productChange"
            >
              <el-option
                v-for="item in filteredOptions1"
                :key="item.productModel"
                :label="`${item.productModelName}`"
                :value="item.productModel"
              />
            </el-select>
          </el-form-item> -->

          <!-- <el-form-item label="产品型号">
            <el-select
              v-model="searchParam.productModel"
              placeholder="请选择产品型号"
              clearable
              filterable
              :filter-method="customFilter"
              @change="productChange"
            >
              <el-option
                v-for="item in filteredOptions"
                :key="item.productModel"
                :label="item.productModel"
                :value="item.productModel"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="监控结果">
            <el-select
              v-model="searchParam.monitorResult"
              placeholder="请选择监控结果"
              clearable
              filterable
            >
              <el-option label="全部" value="" />
              <el-option label="未超控制范围" value="1" />
              <el-option label="超过控制范围" value="2" />
            </el-select>
          </el-form-item> -->

          <!-- <el-form-item label="参数类型">
            <el-select
              v-model="searchParam.processDataType"
              placeholder="请选择参数类型"
              clearable
              filterable
              @change="processTypeChange"
            >
              <el-option label="工艺加工参数" value="2" />
              <el-option label="工艺过程参数" value="3" />
            </el-select>
          </el-form-item> -->

          <el-form-item label="运行参数">
            <el-select
              v-model="searchParam.parameterName"
              placeholder="请选择运行参数"
              e
              clearable
              filterable
              :disabled="!searchParam.deviceId"
              @change="processParameterChange"
            >
              <el-option
                v-for="(item, index) in collectParamList"
                :key="index"
                :label="item.parameterDesc"
                :value="item.parameterName"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="" class="querySelect">
            <el-dropdown @command="queryTypeChange">
              <span class="el-dropdown-link">
                {{ searchParam.queryType == "1" ? "点数统计" : "时间统计"
                }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1"
                    ><span :class="filterColor(1)"
                      >点数统计</span
                    ></el-dropdown-item
                  >
                  <el-dropdown-item command="2"
                    ><span :class="filterColor(2)"
                      >时间统计</span
                    ></el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-input
              v-if="searchParam.queryType == 1"
              v-model="searchParam.pointCount"
              placeholder="请输入"
              clearable
              @keyup.enter="getSingleData"
              style="width: 158px !important; margin-left: 3px"
            >
              <template #append>点</template>
            </el-input>
            <el-date-picker
              v-if="searchParam.queryType == 2"
              v-model="searchParam.collectionTimeSearch"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="getPointTime"
              style="width: 402px !important; margin-left: 3px"
            />
          </el-form-item>
          <!-- <el-form-item label="程序名">
            <el-input
              v-model="searchParam.programName"
              placeholder="请输入程序名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <i-ep-search />
              搜索
            </el-button>
            <el-button @click="handleReset">
              <i-ep-refresh />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-card
        style="height: 400px; min-height: calc(100vh - 120px - 290px)"
        class="contrast_card"
      >
        <div v-if="singleData">
          <esmParamLineChartDouble
            :key="keyId"
            :id="keyId"
            :showName="true"
            :seriesData="singleData"
            chartHeight="350px"
            size="small"
          />

          <!-- 最大值、最小值、平均值、取样频率 -->
          <!-- <div class="detail_line pl-[15px] mt-3 flex justify-center">
            <div class="detail">
              <span>参考值：</span>
              <span>{{
                singleData.doubleData[0]?.parameterStandards ?? "--"
              }}</span>
            </div>
            <div class="detail">
              <span>控制上限：</span>
              <span>{{
                singleData.doubleData[0]?.upperLimitValue ?? "--"
              }}</span>
            </div>
            <div class="detail">
              <span>控制下限：</span>
              <span>{{
                singleData.doubleData[0]?.lowerLimitValue ?? "--"
              }}</span>
            </div>
          </div> -->
        </div>
        <el-empty v-else description="" />
      </el-card>
    </div>
    <!-- 工单弹窗 -->
    <esmworkorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
      key="1"
    />
  </div>
</template>

<script lang="ts" setup>
import request from "@/utils/request";
import { useTable } from "@/utils/useTable";
import router from "@/router";
import dayjs from "dayjs";
import { ArrowDown } from "@element-plus/icons-vue";
import { getMdmproductinfosApi1 } from "@/utils/commonData";
import psmParamLineChart from "@/views/psm/psmParamQuery/components/psmParamLineChart.vue";
import { getSingleDataMock } from "@/views/pcm/pcmMonitoring/index";
import psmworkorderEdit from "@/views/pcm/psmworkorder/components/psmworkorder-edit.vue";
import _ from "lodash-es";

defineOptions({
  name: "EQUESMOPERATINGPARAMQUERYSINGLE",
  inheritAttrs: false,
});

const props = defineProps({
  isContrast: {
    type: Number,
    default: () => {
      return 0;
    },
  },
  keyId: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const { isContrast, keyId } = toRefs(props);

function queryTypeChange(val) {
  searchParam.value.queryType = val;
  if (val == 1) {
    searchParam.value.collectionTimeStart = dayjs(Date.now())
      .subtract(7, "day")
      .format("YYYY-MM-DD");
    searchParam.value.collectionTimeEnd = dayjs(Date.now()).format(
      "YYYY-MM-DD"
    );
    searchParam.value.collectionTimeSearch = [
      dayjs(Date.now()).subtract(7, "day").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  } else {
    searchParam.value.pointCount = "";
  }
}

function filterColor(val) {
  if (searchParam.value.queryType == val) {
    return "c-#409eff font-600";
  }
}

function handleReset() {
  singleData.value = null;
  reset();
}

const activeTabs = ref("1");
function handleSearch() {
  if (activeTabs.value == "1") {
    getSingleData();
    // search();
  } else {
    if (!searchParam.value.collectionTimeStart) {
      ElMessage.error("请选择监控时间");
      return;
    }
    let startTime = dayjs(searchParam.value.collectionTimeStart); // 开始时间
    let endTime = dayjs(searchParam.value.collectionTimeEnd); // 结束时间
    if (endTime.diff(startTime, "hour") > 24 * 7) {
      ElMessage.error("监控时间不能超过七天");
      return;
    }
    // search();
  }
}

// 请求参数
const requestApi = "/dmpDosPcm/psmprocessdata/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processEquipId: "", // 生产线
  pointCount: "100",
  processCode: "", // 工序编号
  processId: "", // 工序id
  // deviceCode: "", // 设备编号
  deviceId: "", // 设备id
  deviceIds: [],
  //   processDataType: "", // 参数类别
  parameterName: "", // 工艺参数
  parameterDesc: "", // 工艺描述
  // productId: "", // 产品型号
  //   monitorResult: "", // 监控结果
  //   programName: "", // 程序名
  //   productModel: "", // 产品型号
  // 监控时间
  collectionTimeStart: dayjs(Date.now())
    .subtract(7, "day")
    .format("YYYY-MM-DD"),
  collectionTimeEnd: dayjs(Date.now()).format("YYYY-MM-DD"),
  collectionTimeSearch: [
    dayjs(Date.now()).subtract(7, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ],
  queryType: "1", // 搜索类别
};

const deleteParam = {
  api: "/system/sysRole/delete",
  data: {},
};

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
// watch(() => initParam, getTableList, { deep: true });

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 获取产品型号列表
const productList = ref<any>([]);
const filteredOptions = ref<any>([]);
async function getProductList() {
  const list: any = await getMdmproductinfosApi1({
    deviceIds: [searchParam.value.deviceId],
  });
  productList.value = list || [];
  filteredOptions.value = [...productList.value];
  filteredOptions1.value = [...productList.value];
}

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productList.value];
    return;
  }
  filteredOptions.value = productList.value.filter((option: any) =>
    option.productModel.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const filteredOptions1 = ref<any>([]);
const customFilter1 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions1.value = [...productList.value];
    return;
  }
  filteredOptions1.value = productList.value.filter((option: any) =>
    option.productModelName.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
  } else {
    searchParam.value.productCode = "";
  }
}

// 获取工序列表
const processCodeList: any = ref([]);
async function getProcessCodeList() {
  const { data } = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processCodeList.value = data;
}
function processChange(code: string) {
  // searchParam.value.deviceCode = "";
  searchParam.value.processEquipId = "";
  searchParam.value.deviceId = "";
  searchParam.value.deviceIds = [];
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  //   searchParam.value.productModel = "";
  collectParamList.value = [];
  if (code) {
    const current: any =
      processCodeList.value?.filter((e: any) => e.processCode === code)[0] ??
      {};
    searchParam.value.processId = current.id || "";
  } else {
    equipList.value = [];
    searchParam.value.processId = "";
  }
  getEquipList();
  getProcessEquipList();
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id?: string) {
  const res: any = await request({
    // url: "/iotadmin/scaequipinfo/getlist",
    url: "/dmpDosPcm/equipmentInfo/getList",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      processEquipId: searchParam.value.processEquipId,
    },
  });
  if (res.code === 200) {
    equipList.value = res.data;
  }
}
function equipChange(ids: string) {
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  collectParamList.value = [];
  //   searchParam.value.productModel = "";
  if (ids) {
    getCollectParamList();
    getProductList();
  } else {
    // searchParam.value.deviceIds = [];
    getProductList();
  }
}

function processTypeChange(id: string) {
  searchParam.value.parameterDesc = "";
  searchParam.value.parameterName = "";

  collectParamList.value = [];
  if (id) {
    getCollectParamList();
  } else {
    getCollectParamList();
  }
}

function processParameterChange(name: string) {
  if (name) {
    const current: any =
      collectParamList.value?.filter((e: any) => e.parameterName === name)[0] ??
      {};
    searchParam.value.parameterDesc = current.parameterDesc || "";
  } else {
    searchParam.value.parameterDesc = "";
  }
}

const collectParamList = ref(<any>[]);
async function getCollectParamList(id?: string) {
  const res: any = await request({
    url: "/iotadmin/scaequipcollectionparam/getRunParamList",
    method: "post",
    data: {
      //   paramType: searchParam.value.processDataType,
      relationIds: [searchParam.value.deviceId],
    },
  });
  if (res.code === 200) {
    collectParamList.value = res.data || [];
  }
}

// 更新创建时间
function getPointTime(data: any) {
  if (data) {
    searchParam.value.collectionTimeStart = data[0];
    searchParam.value.collectionTimeEnd = data[1];
  } else {
    searchParam.value.collectionTimeStart = "";
    searchParam.value.collectionTimeEnd = "";
  }
}

// tab点击事件
function tabClickHandle(e) {
  if (e.index == 1) {
    getSingleData();
  }
}

// 获取单值图数据
const singleLoading = ref(false);
const singleData = ref<any>(null);
async function getSingleData() {
  if (!searchParam.value.deviceId.length) {
    ElMessage.error("请先选择设备");
    return;
  }
  if (!searchParam.value.parameterName) {
    ElMessage.error("请先选择运行参数");
    return;
  }
  if (
    searchParam.value.queryType == 1 &&
    !/^(0|[1-9][0-9]*)$/.test(searchParam.value.pointCount)
  ) {
    ElMessage.error("显示点数应为正整数");
    return;
  }
  if (
    searchParam.value.queryType == 1 &&
    Number(searchParam.value.pointCount) > 10000
  ) {
    ElMessage.error("点数不能大于10000");
    return;
  }
  if (
    searchParam.value.queryType == 2 &&
    !searchParam.value.collectionTimeStart
  ) {
    ElMessage.error("请选择时间且不能超过七天");
    return;
  }
  let startTime = dayjs(searchParam.value.collectionTimeStart); // 开始时间
  let endTime = dayjs(searchParam.value.collectionTimeEnd); // 结束时间
  if (
    searchParam.value.queryType == 2 &&
    endTime.diff(startTime, "hour") > 24 * 7
  ) {
    ElMessage.error("请选择时间且不能超过七天");
    return;
  }
  //   if (!searchParam.value.productModel) {
  //     ElMessage.warning("请选择产品型号");
  //     return;
  //   }
  // if (!searchParam.value.programName) {
  //   ElMessage.warning("请填写程序名");
  //   return;
  // }
  searchParam.value.deviceIds = [searchParam.value.deviceId];
  singleData.value = null;
  singleLoading.value = true;
  const params = JSON.parse(JSON.stringify(searchParam.value));
  if (params.queryType == 2) {
    params.pointCount = undefined;
  }
  if (params.queryType == 1) {
    params.collectionTimeStart = undefined;
    params.collectionTimeEnd = undefined;
    params.collectionTimeSearch = undefined;
  }
  //   const { data }: any = await request({
  //     url: "/iotadmin/esmRunData/multiParamCurve",
  //     method: "post",
  //     data: {
  //       ...params,
  //       parameterDescList: [params.parameterDesc],
  //       parameterNameList: [params.parameterName],
  //     },
  //   })
  const { data }: any = await request({
    url: "/iotadmin/esmRunData/multiCurve",
    method: "post",
    data: params,
  })
    .finally(() => {
      singleLoading.value = false;
    })
    .catch((e) => {});
  singleData.value = {
    doubleData: data,
    paramName: searchParam.value.parameterDesc,
  };
  singleLoading.value = false;

  // 模拟
  // singleData.value = {};
  // singleLoading.value = true;
  // setTimeout(() => {
  //   singleData.value = {
  //     doubleData: [getSingleDataMock(100), getSingleDataMock(100)],
  //     paramName: searchParam.value.parameterDesc,
  //   };
  //   console.log("singleData.value", singleData.value);
  //   singleLoading.value = false;
  // }, 1000);
}

onMounted(() => {
  getProcessEquipList();
  getEquipList();
  getProcessCodeList();
  // 获取产品型号列表
  getProductList();
  getTableList();
  getWorkshopSectionList();
});

// 打开工单详情
function openWorkOrder(item: any) {
  if (item.orderNo) {
    openDialogdetail({ id: item.orderNo });
  }
}
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmworkorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开工单管理表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工单管理详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
const changeWorkshopSection = () => {
  searchParam.value.processEquipId = "";
  searchParam.value.processCode = "";
  searchParam.value.processId = "";
  searchParam.value.deviceId = "";
  //   searchParam.value.productModel = "";
  processCodeList.value = [];
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  collectParamList.value = [];
  getProcessListByWorkshopSection();
  getProcessEquipList();
  getEquipList();
};

const getProcessListByWorkshopSection = async () => {
  if (searchParam.value.workshopSectionId) {
    await request({
      url: `mdm/mdmworkshopsection/getDetails`,
      method: "post",
      data: { id: searchParam.value.workshopSectionId },
    }).then((res) => {
      processCodeList.value = res.data
        ? res.data.map(({ processId, processCode }) => ({
            id: processId,
            processName: processCode,
            processCode,
          }))
        : [];
    });
  } else {
    await getProcessCodeList();
  }
};

const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};

// 获取工序列表
const processEquipList: any = ref([]);
async function getProcessEquipList() {
  searchParam.value.processEquipId = "";
  processEquipList.value = [];
  const { data } = await request({
    // url: `/mdm/mdmprocess/getList`,
    url: "/mdm/mdmprocessequip/getList",
    method: "post",
    data: {
      workshopSectionId: searchParam.value.workshopSectionId,
      processId: searchParam.value.processId,
    },
  });
  processEquipList.value = data;
}
function processEquipChange() {
  searchParam.value.deviceId = "";
  //   searchParam.value.equipId = "";
  //   searchParam.value.equipCode = "";
  //   searchParam.value.productModel = "";
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  collectParamList.value = [];
  getEquipList();
  getProductList();
}
</script>

<style lang="scss" scoped>
:deep(.app-container .el-tabs--border-card) {
  box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08);
  border: none;
}
:deep(.select-device) {
  .el-tag {
    padding: 0 4px;
  }
}
:deep(.el-descriptions--small .el-descriptions__header) {
  margin-top: 12px;
  margin-bottom: 4px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 65px;
}

.doubleData0 {
  :deep(.el-descriptions__header) {
    margin-top: 0px !important;
  }
}
// .el-tabs:nth-child(2) {
//   :deep(.el-tabs__content) {
//     background-color: aqua;
//     padding: 15px 4px;
//   }
// }
.detail_line {
  overflow: hidden;
  .detail {
    font-size: 14px;
    overflow: hidden;
    float: left;
    margin-right: 35px;
    line-height: 28px;
    color: #4e5969;
    span {
      display: block;
      float: left;
      word-break: break-all;
    }
    span:nth-child(1) {
      margin-right: 0px;
    }
  }
}

.querySelect .el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  .el-icon {
    margin-left: 1px;
    width: 13px;
    margin-top: 1px;
  }
}
:deep(.el-empty) {
  height: 380px;
  .el-empty__image {
    width: 120px;
  }
}
.el-card {
  box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08);
  border: none;
}
</style>
